package com.example.partner.listener;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class EndlessScrollListener extends RecyclerView.OnScrollListener {
    private LinearLayoutManager layoutManager;
    private LoadMoreListener loadMoreListener;

    public EndlessScrollListener(LinearLayoutManager layoutManager, LoadMoreListener loadMoreListener) {
        this.layoutManager = layoutManager;
        this.loadMoreListener = loadMoreListener;
    }
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        int visibleItemCount = layoutManager.getChildCount();
        int totalItemCount = layoutManager.getItemCount();
        int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
        if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                && firstVisibleItemPosition >= 0
                && totalItemCount >= LoadMoreListener.MIN_ITEMS_BEFORE_LOAD) {
            // 滑动到底部
            loadMoreListener.onLoadMore();
        }
    }
    public interface LoadMoreListener {
        int MIN_ITEMS_BEFORE_LOAD = 5; // 规定剩下多少项时开始加载更多
        void onLoadMore();
    }
}
